package com.apollographql.apollo.internal.fetcher;

import com.apollographql.apollo.api.internal.ApolloLogger;
import com.apollographql.apollo.exception.ApolloException;
import com.apollographql.apollo.fetcher.ResponseFetcher;
import com.apollographql.apollo.interceptor.ApolloInterceptor;
import com.apollographql.apollo.interceptor.ApolloInterceptorChain;
import java.util.concurrent.Executor;

public final class CacheFirstFetcher implements ResponseFetcher {
    @Override // com.apollographql.apollo.fetcher.ResponseFetcher
    public ApolloInterceptor provideInterceptor(ApolloLogger apolloLogger) {
        return new CacheFirstInterceptor();
    }

    private static final class CacheFirstInterceptor implements ApolloInterceptor {
        volatile boolean disposed;

        private CacheFirstInterceptor() {
        }

        @Override // com.apollographql.apollo.interceptor.ApolloInterceptor
        public void interceptAsync(final InterceptorRequest request, final ApolloInterceptorChain chain, final Executor dispatcher, final CallBack callBack) {
            chain.proceedAsync(request.toBuilder().fetchFromCache(true).build(), dispatcher, new CallBack() {
                /* class com.apollographql.apollo.internal.fetcher.CacheFirstFetcher.CacheFirstInterceptor.AnonymousClass1 */

                @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                public void onResponse(InterceptorResponse response) {
                    callBack.onResponse(response);
                }

                @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                public void onFailure(ApolloException e) {
                    if (!CacheFirstInterceptor.this.disposed) {
                        chain.proceedAsync(request.toBuilder().fetchFromCache(false).build(), dispatcher, callBack);
                    }
                }

                @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                public void onCompleted() {
                    callBack.onCompleted();
                }

                @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                public void onFetch(FetchSourceType sourceType) {
                    callBack.onFetch(sourceType);
                }
            });
        }

        @Override // com.apollographql.apollo.interceptor.ApolloInterceptor
        public void dispose() {
            this.disposed = true;
        }
    }
}
